package com.dhl.deliver.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dhl.deliver.dto.AddressDto;
import com.dhl.deliver.entity.Address;
import com.dhl.deliver.service.IAddressService;
import com.dhl.deliver.service.IUserService;
import com.dhl.deliver.utils.Result;
import com.dhl.deliver.utils.ResultUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author dhl
 * @since 2020-07-15
 */
@RestController
@RequestMapping("/address")
@Api("用户收货地址管理")
public class AddressController {

    @Resource
    IAddressService addressService;
    @Resource
    IUserService userService;

    @ApiOperation("获取当前的用户收货地址")
    @GetMapping("/getAddressByPage")
    public Result getAddressByPage(HttpServletRequest request){  //分页获取数据
        QueryWrapper<Address> queryWrapper = new QueryWrapper<Address>().eq("user_id", request.getSession().getAttribute("id"));
//        IPage<Address> resultPage = addressService.page(page,queryWrapper);
//        GridResultWrapper resultWrapper = new GridResultWrapper(resultPage.getTotal(),resultPage.getRecords() );
        Result result = ResultUtil.success(addressService.list(queryWrapper));
        return result;
    }

    @ApiOperation("添加用户收货地址")
    @PostMapping("/addAddress")
    public Result addAddress(HttpServletRequest request,@RequestBody AddressDto addressDto){
        String userId = userService.getCurrentUserId(request);
        Address address =new Address();
        BeanUtils.copyProperties(addressDto,address);
        address.setUserId(userId);
        addressService.save(address);
        Result result = ResultUtil.success();
        return result;
    }
    @ApiOperation("删除用户收货地址")
    @PostMapping("/deleteAddress")
    public Result deleteAddress(String addressId){
        Map<String,Object> map=new HashMap<String,Object>();
        map.put("id",addressId);
        if(addressService.removeByMap(map)){
            System.out.println(addressService.getById(addressId));
            return ResultUtil.success("删除地址成功");
        }
        return ResultUtil.error(500,"删除失败");
    }
}
